<template>
    <div class="organization-container">
        <!-- 搜索区域 -->
        <el-card class="search-card">
            <el-form :model="searchForm" :inline="true" class="search-form">
                <el-form-item label="组织">
                    <el-input v-model="searchForm.organizationName" placeholder="请输入组织名称/编号" clearable />
                </el-form-item>
                <el-form-item label="状态">
                    <el-select v-model="searchForm.organizationState" placeholder="请选择状态" clearable>
                        <el-option label="启用" :value="1" />
                        <el-option label="停用" :value="0" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleSearch">查询</el-button>
                    <el-button @click="handleReset">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>

        <!-- 操作按钮区域 -->
        <el-card class="action-card">
            <el-button type="primary" @click="handleAdd">新增</el-button>
            <el-button type="success" @click="handleBatchEnable"
                :disabled="multipleSelection.length === 0">批量启用</el-button>
            <el-button type="warning" @click="handleBatchDisable"
                :disabled="multipleSelection.length === 0">批量停用</el-button>
            <el-button type="danger" @click="handleBatchDelete"
                :disabled="multipleSelection.length === 0">批量删除</el-button>
        </el-card>

        <!-- 树形表格 -->
        <el-card class="table-card">
            <el-table :data="organizationTreeData" style="width: 100%" row-key="id"
                :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
                @selection-change="handleSelectionChange" height="500px" default-expand-all>
                <el-table-column type="selection" width="55" />
                <el-table-column type="index" label="序号" width="80" />
                <el-table-column property="code" label="组织编号" width="120" />
                <el-table-column property="label" label="组织名称" width="300" />
                <el-table-column property="sort" label="排序" width="80" />
                <el-table-column property="state" label="状态" width="80">
                    <template #default="{ row }">
                        <el-tag :type="row.state === 1 ? 'success' : 'danger'">
                            {{ row.state === 1 ? '启用' : '停用' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="160" fixed="right">
                    <template #default="{ row }">
                        <el-button link type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
                        <el-button link type="danger" size="small" @click="handleDelete(row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>

        <!-- 新增/编辑对话框 -->
        <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px" @close="handleDialogClose">
            <el-form ref="organizationFormRef" :model="organizationForm" :rules="organizationFormRules"
                label-width="100px">
                <el-form-item label="上级组织" prop="organizationParentId">
                    <el-tree-select v-model="organizationForm.organizationParentId" :data="organizationTreeData"
                        :props="{ value: 'id', label: 'label', children: 'children' }" placeholder="请选择上级组织" clearable
                        check-strictly :render-after-expand="false" class="form-input" />
                </el-form-item>
                <el-form-item label="组织编号 *" prop="organizationCode">
                    <el-input v-model="organizationForm.organizationCode" placeholder="自动获取系统编号" clearable readonly
                        class="form-input">
                        <template #append>
                            <el-button @click="generateOrganizationCode" :loading="generatingCode">自动生成</el-button>
                        </template>
                    </el-input>
                </el-form-item>
                <el-form-item label="组织名称 *" prop="organizationName">
                    <el-input v-model="organizationForm.organizationName" placeholder="请输入组织名称" class="form-input" />
                </el-form-item>
                <el-form-item label="排序" prop="organizationSort">
                    <el-input-number v-model="organizationForm.organizationSort" :min="0" class="form-input" />
                </el-form-item>
                <el-form-item label="状态" prop="organizationState">
                    <el-radio-group v-model="organizationForm.organizationState">
                        <el-radio :label="1">启用</el-radio>
                        <el-radio :label="0">停用</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleSave">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox, type FormRules, type FormInstance } from 'element-plus'
import myaxios from "@/http/MyAxios";

// 搜索表单数据
const searchForm = reactive({
    organizationName: '',
    organizationState: null
})

// 组织树形数据
const organizationTreeData = ref<any[]>([])

// 多选数据
const multipleSelection: any = ref([])

// 生成编号状态
const generatingCode = ref(false)

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)
const organizationFormRef = ref<FormInstance>()

// 组织表单数据
const organizationForm = reactive({
    organizationId: null,
    organizationParentId: null,
    organizationCode: '',
    organizationName: '',
    organizationSort: 0,
    organizationState: 1,
})

// 表单验证规则
const organizationFormRules: FormRules = {
    organizationName: [
        { required: true, message: '请输入组织名称', trigger: 'blur' }
    ]
}

// 获取组织树形数据
const getOrganizationTree = () => {
    myaxios({
        url: "/api/Organization/GetOrganizationTree",
        method: "get",
        params: {
            parentId: 0  // 获取顶级组织及其子组织
        }
    })
        .then(res => {
            organizationTreeData.value = res.data
        })
        .catch(err => {
            console.log(err)
            ElMessage.error('获取数据失败')
        })
}

// 搜索
const handleSearch = () => {
    // 如果有搜索条件，可以传递给后端进行过滤
    const params: any = { parentId: 0 }

    if (searchForm.organizationName) {
        params.organizationName = searchForm.organizationName
    }
    if (searchForm.organizationState !== null) {
        params.organizationState = searchForm.organizationState
    }

    myaxios({
        url: "/api/Organization/GetOrganizationTree",
        method: "get",
        params: params
    })
        .then(res => {
            if (res.data.code === 200) {
                organizationTreeData.value = res.data.data || []
            } else {
                ElMessage.error(res.data.message || '获取数据失败')
            }
        })
        .catch(err => {
            console.log(err)
            ElMessage.error('获取数据失败')
        })
}

// 重置搜索
const handleReset = () => {
    searchForm.organizationName = ''
    searchForm.organizationState = null
    getOrganizationTree()
}

// 多选变化
const handleSelectionChange = (selection: any[]) => {
    multipleSelection.value = selection
}

// 重置表单
const resetOrganizationForm = () => {
    organizationForm.organizationId = null
    organizationForm.organizationParentId = null
    organizationForm.organizationCode = ''
    organizationForm.organizationName = ''
    organizationForm.organizationSort = 0
    organizationForm.organizationState = 1
}

// 关闭对话框
const handleDialogClose = () => {
    organizationFormRef.value?.resetFields()
    resetOrganizationForm()
}

// 生成组织编号
const generateOrganizationCode = async () => {
    generatingCode.value = true
    try {
        // 调用编号规则接口生成编号
        // 根据 targetCode 或 targetName 获取编号规则并生成编号
        // 假设接口是 /api/Number/GenerateNumber，参数是 targetCode 或 targetName
        const res = await myaxios({
            url: '/api/Number/GenerateNumber',
            method: 'get',
            params: {
                targetCode: 'Organization',
                targetName: '组织机构'
            }
        })

        if (res?.data?.code === 200 && res?.data?.data) {
            organizationForm.organizationCode = res.data.data
            ElMessage.success('编号生成成功')
        } else {
            // 如果接口不存在或失败，尝试其他方式
            throw new Error(res?.data?.message || '生成编号失败')
        }
    } catch (err: any) {
        console.error('生成编号失败:', err)
        // 如果接口不存在，使用备用方案：根据编号规则查询并生成
        try {
            const ruleRes = await myaxios({
                url: '/api/Number/QueryNumberingRules',
                method: 'get',
                params: {
                    targetCode: 'Organization',
                    targetName: '组织机构'
                }
            })

            if (ruleRes?.data?.code === 200 && Array.isArray(ruleRes.data.data) && ruleRes.data.data.length > 0) {
                const rule = ruleRes.data.data[0]
                // 根据规则生成编号（这里需要根据实际规则逻辑生成）
                const now = new Date()
                const pad = (n: number, len = 2) => `${n}`.padStart(len, '0')
                const timeRule = (rule.timeRule || '').split(',').filter(Boolean)
                const order: string[] = ['YYYY', 'YY', 'MM', 'DD', 'HH', 'MI', 'SS']
                const sorted = timeRule.sort((a: string, b: string) => {
                    const indexA = order.indexOf(a)
                    const indexB = order.indexOf(b)
                    if (indexA === -1 && indexB === -1) return 0
                    if (indexA === -1) return 1
                    if (indexB === -1) return -1
                    return indexA - indexB
                })

                let datePart = ''
                sorted.forEach((seg: string) => {
                    switch (seg) {
                        case 'YYYY':
                            datePart += String(now.getFullYear())
                            break
                        case 'YY':
                            datePart += String(now.getFullYear()).slice(-2)
                            break
                        case 'MM':
                            datePart += pad(now.getMonth() + 1)
                            break
                        case 'DD':
                            datePart += pad(now.getDate())
                            break
                        case 'HH':
                            datePart += pad(now.getHours())
                            break
                        case 'MI':
                            datePart += pad(now.getMinutes())
                            break
                        case 'SS':
                            datePart += pad(now.getSeconds())
                            break
                    }
                })

                const seq = '1'.padStart(rule.serialLength || 3, '0')
                organizationForm.organizationCode = (rule.codePrefix || '') + datePart + seq
                ElMessage.success('编号生成成功')
            } else {
                ElMessage.warning('未找到对应的编号规则，请先在编号规则中配置')
            }
        } catch (ruleErr) {
            console.error('获取编号规则失败:', ruleErr)
            ElMessage.error('生成编号失败，请稍后重试')
        }
    } finally {
        generatingCode.value = false
    }
}

// 新增组织
const handleAdd = () => {
    dialogTitle.value = '新增组织'
    isEdit.value = false
    resetOrganizationForm()
    dialogVisible.value = true
}

// 保存组织
const handleSave = async () => {
    // 如果是新增且没有输入编号，自动生成
    if (!isEdit.value && !organizationForm.organizationCode) {
        await generateOrganizationCode()
        // 如果生成失败，不继续保存
        if (!organizationForm.organizationCode) {
            return
        }
    }

    organizationFormRef.value?.validate((valid) => {
        if (valid) {
            const url = isEdit.value ? '/api/Organization/UpdateOrganization' : '/api/Organization/CreateOrganization'
            const method = 'post'
            myaxios({
                url: url,
                method: method,
                data: organizationForm
            })
                .then(res => {
                    if (res.data.code === 200) {
                        ElMessage.success(res.data.message || '保存成功')
                        dialogVisible.value = false
                        getOrganizationTree()
                    } else {
                        ElMessage.error(res.data.message || '保存失败')
                    }
                })
                .catch(err => {
                    console.log(err)
                    ElMessage.error('保存失败')
                })
        } else {
            ElMessage.warning('请填写必填项')
        }
    })
}

// 编辑组织
const handleEdit = (row: any) => {
    dialogTitle.value = '编辑组织'
    isEdit.value = true
    resetOrganizationForm()
    dialogVisible.value = true

    // 反填表单数据
    organizationForm.organizationId = row.id || null
    organizationForm.organizationParentId = row.parentId || null
    organizationForm.organizationCode = row.code || ''
    organizationForm.organizationName = row.label || ''
    organizationForm.organizationSort = row.sort || 0
    organizationForm.organizationState = row.state !== undefined ? row.state : 1
}

// 删除单个组织
const handleDelete = (row: any) => {
    ElMessageBox.confirm(
        '确认删除这个组织信息吗?',
        '警告',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            myaxios({
                url: "/api/Organization/DeleteOrganization",
                method: "delete",
                params: { organizationId: row.id }
            })
                .then(res => {
                    if (res.data.code === 200) {
                        getOrganizationTree()
                        ElMessage.success(res.data.message || '删除成功')
                    } else {
                        ElMessage.error(res.data.message || '删除失败')
                    }
                })
                .catch(err => {
                    console.log(err)
                    ElMessage.error('删除失败')
                })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '已取消',
            })
        })
}

// 批量删除
const handleBatchDelete = () => {
    if (multipleSelection.value.length === 0) {
        ElMessage.warning('请选择要删除的组织')
        return
    }
    ElMessageBox.confirm(
        '确认删除这些组织信息吗?',
        '警告',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            const organizationIds = multipleSelection.value.map((x: any) => x.id)
            myaxios({
                url: "/api/Organization/DeleteOrganizations",
                method: "post",
                data: {
                    ids: organizationIds
                }
            })
                .then(res => {
                    if (res.data.code === 200) {
                        getOrganizationTree()
                        ElMessage.success(res.data.message || '删除成功')
                    } else {
                        ElMessage.error(res.data.message || '删除失败')
                    }
                })
                .catch(err => {
                    console.log(err)
                    ElMessage.error('删除失败')
                })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '已取消',
            })
        })
}

// 批量启用
const handleBatchEnable = () => {
    if (multipleSelection.value.length === 0) {
        ElMessage.warning('请选择要启用的组织')
        return
    }
    const organizationIds = multipleSelection.value.map((x: any) => x.id)
    myaxios({
        url: "/api/Organization/EnableOrganizations",
        method: "post",
        data: {
            ids: organizationIds
        }
    })
        .then(res => {
            if (res.data.code === 200) {
                getOrganizationTree()
                ElMessage.success(res.data.message || '启用成功')
            } else {
                ElMessage.error(res.data.message || '启用失败')
            }
        })
        .catch(err => {
            console.log(err)
            ElMessage.error('启用失败')
        })
}

// 批量停用
const handleBatchDisable = () => {
    if (multipleSelection.value.length === 0) {
        ElMessage.warning('请选择要停用的组织')
        return
    }
    const organizationIds = multipleSelection.value.map((x: any) => x.id)
    myaxios({
        url: "/api/Organization/DisableOrganizations",
        method: "post",
        data: {
            ids: organizationIds
        }
    })
        .then(res => {
            if (res.data.code === 200) {
                getOrganizationTree()
                ElMessage.success(res.data.message || '停用成功')
            } else {
                ElMessage.error(res.data.message || '停用失败')
            }
        })
        .catch(err => {
            console.log(err)
            ElMessage.error('停用失败')
        })
}

// 页面加载时获取数据
onMounted(() => {
    getOrganizationTree()
})
</script>

<style scoped>
.organization-container {
    padding: 20px;
}

.search-card,
.action-card,
.table-card {
    margin-bottom: 20px;
}

.search-form .el-form-item {
    margin-bottom: 0;
}

.el-input,
.el-select {
    width: 200px;
}

/* 对话框表单输入框统一宽度 */
:deep(.form-input) {
    width: 400px !important;
}

:deep(.form-input.el-input-number) {
    width: 400px !important;
}

:deep(.form-input .el-input__wrapper) {
    width: 100% !important;
}

:deep(.form-input.el-tree-select) {
    width: 400px !important;
}

:deep(.form-input.el-tree-select .el-input__wrapper) {
    width: 100% !important;
}
</style>